"""
简易学生信息管理系统
    版本01：txt存储学生信息版本
"""
import os

file_name = "./student.txt"


def insert():
    student_list = []
    while True:
        id = input("请输入学生ID：")
        if not id:
            print("id不能为空！")
            break
        name = input("请输入学生姓名:")
        if not name:
            print("学生姓名不能为空!")
            break
        try:
            english = int(input("请输入英语成绩："))
            java = int(input("请输入java成绩："))
            python = int(input("请输入python成绩："))
        except:
            print("输入错误，请重新输入")
            continue
        student = {"id": id, "name": name, "english": english, "java": java, "python": python}
        student_list.append(student)
        answer = input("是否继续添加?(y/n):")
        if answer == 'y':
            continue
        else:
            break
    # 保存学生信息
    save(student_list)
    print("学生信息录入完毕!")


def save(lst: list):
    """
    保存学生信息
    :param lst: 学生信息列表
    :return:
    """
    try:
        student_txt = open(file_name, "a", encoding="UTF-8")
    except:
        student_txt = open(file_name, "w", encoding="UTF-8")
    for item in lst:
        student_txt.write(str(item) + '\n')
    student_txt.close()


def select(student_id) -> list:
    while True:
        res_lst = []
        if not student_id:
            student_id = input("请输入要查询的学生姓名(为空则查询全部学生):")
        if os.path.exists(file_name):
            with open(file_name, "r", encoding="UTF-8") as rfile:
                for item in rfile.readlines():
                    dict_data = eval(item)
                    if not student_id or dict_data['id'] == student_id:
                        res_lst.append(dict_data)
        show_student(res_lst)
        answer = input("是否继续查询?(y/n):")
        if answer == 'n' or answer == 'N':
            break
        student_id = None
    return res_lst


def delete():
    while True:
        student_id = input("请输入要查询的学生编号(为空则不删除):")
        if student_id != '':
            if os.path.exists(file_name):
                with open(file_name, "r", encoding="UTF-8") as rfile:
                    student_old = rfile.readlines()
            else:
                student_old = []
            flag = False  # 标记是否删除
            if student_old:
                with open(file_name, "w", encoding="UTF-8") as wfile:
                    for item in student_old:
                        w_data = dict(eval(item))
                        if w_data['id'] != student_id:
                            wfile.write(str(w_data) + '\n')
                        else:
                            flag = True
                    if flag:
                        print(f"id为{student_id}的学生信息已删除")
                    else:
                        print(f"没有找到id为{student_id}的学生信息")
            else:
                print("无学生信息")
                break
            show()
            answer = input("是否继续删除?(y/n):")
            if answer == 'n' or answer == 'N':
                break


def update():
    student_id = input("请输入修改的学生ID:")
    # 查找修改的学生是否存在
    if student_id:
        if os.path.exists(file_name):
            with open(file_name, "r", encoding="UTF-8") as rfile:
                student_old = rfile.readlines()
        else:
            student_old = []
        if student_old:
            with open(file_name, "w", encoding="UTF-8") as wfile:
                flag = False  # 是否修改成功标识
                for item in student_old:
                    dct = eval(item)
                    if dct['id'] == student_id:
                        print("找到这名学生，可以修改他的信息了!")
                        while True:
                            try:
                                name = input("请输入姓名:")
                                english = int(input("请输入英语成绩："))
                                java = int(input("请输入java成绩："))
                                python = int(input("请输入python成绩："))
                            except:
                                print("输入错误，请重新输入!")
                            else:
                                break
                        dct = {"id": student_id, "name": name, "english": english, "java": java, "python": python}
                        flag = True
                    wfile.write(str(dct) + "\n")
                if flag:
                    print("修改成功!!!")
                else:
                    print("无该学生信息")
    else:
        print("无学生信息")
    show()
    answer = input("是否继续修改其他学生信息?(y/n):")
    if answer == 'y' or answer == 'Y':
        update()


def sort():
    if os.path.exists(file_name):
        # 获取学生信息数据
        student_list = []
        with open(file_name, "r", encoding="UTF-8") as rfile:
            for item in rfile.readlines():
                student_list.append(eval(item))
        # 展示全部学生信息
        show_student(student_list)
        # 选择排序的反向(升序/降序)
        asc_or_desc = input("请选择排序方式(1:降序 0:升序)：")
        asc_or_desc_bool = None
        if asc_or_desc == '0':
            asc_or_desc_bool = False
        elif asc_or_desc == '1':
            asc_or_desc_bool = True
        else:
            print("输入错误,请重新输入:")
            sort()

        sort_key_id = input("请选择排序的字段(1.英语成绩 2.java成绩 3.python成绩 0.总成绩):")
        if sort_key_id == '1':
            student_list.sort(key=lambda x: x["english"], reverse=asc_or_desc_bool)
        elif sort_key_id == '2':
            student_list.sort(key=lambda x: x["java"], reverse=asc_or_desc_bool)
        elif sort_key_id == '3':
            student_list.sort(key=lambda x: x["python"], reverse=asc_or_desc_bool)
        elif sort_key_id == '0':
            student_list.sort(key=lambda x: x["english"] + x["python"] + x["java"], reverse=asc_or_desc_bool)
        else:
            print("输入错误，请重新输入")
            sort()
        # 输出排序结果
        show_student(student_list)
    else:
        return


def total():
    if os.path.exists(file_name):
        with open(file_name, "r", encoding="UTF-8") as rfile:
            student_lst = rfile.readlines()
            if student_lst:
                print(f"一共有{len(student_lst)}个学生")
            else:
                print("暂未录入学生信息")
    else:
        print("暂未保存学生信息!!!")


def show_student(lst: list[dict]):
    if not lst:
        return
    format_title = "{:^6}\t{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:^8}"
    print(format_title.format("ID", "姓名", "英语成绩", "java成绩", "python成绩", "总成绩"))
    for item in lst:
        print(format_title.format(item["id"],
                                  item["name"],
                                  item.get("english"),
                                  item["java"],
                                  item["python"],
                                  int(item["english"]) + int(item["java"]) + int(item["python"])
                                  ))


def show():
    if os.path.exists(file_name):
        stu_lst = []
        with open(file_name, "r", encoding="UTF-8") as rfile:
            for item in rfile.readlines():
                dict_data = eval(item)
                stu_lst.append(dict_data)
        show_student(stu_lst)
    else:
        print("暂未保存过学生信息")


def main():
    while True:
        main_menu()
        choice = int(input("请选择:"))
        if choice in [0, 1, 2, 3, 4, 5, 6, 7]:
            if choice == 0:
                answer = input("您确定要退出系统吗？(y/n):")
                if answer == 'y' or answer == 'Y':
                    print("谢谢您的使用!!!")
                    break
                else:
                    continue
            elif choice == 1:
                # 录入学生信息
                insert()
            elif choice == 2:
                # 查找学生信息
                select(None)
            elif choice == 3:
                # 删除学生信息
                delete()
            elif choice == 4:
                # 修改学生信息
                update()
            elif choice == 5:
                # 排序
                sort()
            elif choice == 6:
                # 统计学生总人数
                total()
            elif choice == 7:
                # 显示所有学生信息
                show()


def main_menu():
    print("================学生信息管理系统======================")
    print("-------------------功能菜单--------------------------")
    print("\t\t\t\t1.录入学生信息")
    print("\t\t\t\t2.查找学生信息")
    print("\t\t\t\t3.删除学生信息")
    print("\t\t\t\t4.修改学生信息")
    print("\t\t\t\t5.排序")
    print("\t\t\t\t6.统计学生总人数")
    print("\t\t\t\t7.显示所有学生信息")
    print("\t\t\t\t0.退出系统")
    print("---------------------------------------------------")


if __name__ == '__main__':
    main()
